/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ABMProveedores.java
 *
 * Created on 26/07/2011, 16:05:02
 */

package ventanas;

import conexiones.AdministradorDeConexiones;
import dao.ProveedoresDao;
import java.awt.Frame;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Articulo;
import modelo.Proveedor;

/**
 *
 * @author Cristian Perez
 */
public class ABMProveedores extends javax.swing.JDialog {

    DefaultTableModel modeloTablaProveeedores = new DefaultTableModel();
    ArrayList<Object> listaProveedores;

    /** Creates new form ABMProveedores */
    public ABMProveedores(Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        modeloTablaProveeedores = (DefaultTableModel) jTable1.getModel();
        jTable1.setModel(modeloTablaProveeedores);
        
        estructurarTabla();
        listarProveedores();
        //jTable1.setAutoResizeMode(jTable1.AUTO_RESIZE_OFF);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        lblBuscar = new javax.swing.JLabel();
        txtBusqueda = new javax.swing.JTextField();
        btnVerDatosComp = new javax.swing.JButton();
        btnListarTodos = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        btnSalir = new javax.swing.JButton();
        btnNuevo = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEstCuenta = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consulta de Proveedores");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jTable1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 970, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblBuscar.setFont(new java.awt.Font("Tahoma", 1, 12));
        lblBuscar.setText("Buscar Proveedor: ");

        txtBusqueda.setFont(new java.awt.Font("Tahoma", 1, 11));
        txtBusqueda.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtBusquedaFocusLost(evt);
            }
        });
        txtBusqueda.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBusquedaKeyReleased(evt);
            }
        });

        btnVerDatosComp.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnVerDatosComp.setText("Ver Datos Completos");
        btnVerDatosComp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerDatosCompActionPerformed(evt);
            }
        });

        btnListarTodos.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnListarTodos.setText("Ver Lista Completa");
        btnListarTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnListarTodosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblBuscar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(75, 75, 75)
                .addComponent(btnVerDatosComp)
                .addGap(51, 51, 51)
                .addComponent(btnListarTodos)
                .addContainerGap(94, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnVerDatosComp, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnListarTodos, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        btnSalir.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnNuevo.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnNuevo.setText("Nuevo Proveedor");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEliminar.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnModificar.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnEstCuenta.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnEstCuenta.setText("Estado de Cuenta");
        btnEstCuenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEstCuentaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(btnNuevo)
                .addGap(35, 35, 35)
                .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(44, 44, 44)
                .addComponent(btnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(58, 58, 58)
                .addComponent(btnEstCuenta)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
                .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEstCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-986)/2, (screenSize.height-484)/2, 986, 484);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        // TODO add your handling code here:
        AltaProveedores ventAltaProv = new AltaProveedores(this, true);
        ventAltaProv.setVisible(true);
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (jTable1.getRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No existen proveedores para modificar...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() == 0){
            JOptionPane.showMessageDialog(this, "No ha seleccionado ningun proveedor para modificar...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() == 1 ) {
            ModificarProveedor ventaModProv = new ModificarProveedor(this, true);
            ventaModProv.mostrarProveedor((Proveedor) listaProveedores.get(jTable1.getSelectedRow()));
            ventaModProv.setVisible(true);
        }
        else if (jTable1.getSelectedRowCount() > 1) {
            JOptionPane.showMessageDialog(this, "No puede modificar mas de un proveedor a la vez...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        // TODO add your handling code here:
        listarProveedores();
    }//GEN-LAST:event_formWindowGainedFocus

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (jTable1.getRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No existen proveedores a eliminar!!!", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() == 0){
            JOptionPane.showMessageDialog(this, "No ha seleccionado ningun proveedor para eliminar...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() < 2 ) {
            int rta = JOptionPane.showConfirmDialog(this,
                                        "Esta seguro de eliminar el Proveedor ?",
                                        "Eliminar",
                                        JOptionPane.YES_NO_OPTION);

            // Si no desea borrarlo, entonces no lo borra
            if(rta == JOptionPane.NO_OPTION) {
                return;
            }
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                /*Le pedimos a la listaAuxiliar el articulo que vamos a borrar*/
                Proveedor proveedorAborrar = (Proveedor) listaProveedores.get(jTable1.getSelectedRow());
                //Eliminamos el item de la mesa, se borra de la base de datos
                ProveedoresDao.getInstance().eliminar(conn, proveedorAborrar);
                listarProveedores();
            }
            catch(Exception e) {e.printStackTrace();}

        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnVerDatosCompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerDatosCompActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (jTable1.getRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No existen proveedores para consultar...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() == 0){
            JOptionPane.showMessageDialog(this, "No ha seleccionado ningun proveedor para consultar...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() == 1 ) {
            ConsultarProveedor ventaConsProv = new ConsultarProveedor(this, true);
            ventaConsProv.mostrarProveedor((Proveedor) listaProveedores.get(jTable1.getSelectedRow()));
            ventaConsProv.setVisible(true);
        }
        else if (jTable1.getSelectedRowCount() > 1) {
            JOptionPane.showMessageDialog(this, "No puede consultar mas de un proveedor a la vez...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnVerDatosCompActionPerformed

    private void btnListarTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListarTodosActionPerformed
        // TODO add your handling code here:
        listarProveedores();
    }//GEN-LAST:event_btnListarTodosActionPerformed

    private void txtBusquedaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusquedaKeyReleased
        // TODO add your handling code here:
        if (evt.getKeyCode() != 27) {
            filtrarRazonSocial();
        }
        else {
            txtBusqueda.setText("");
            btnListarTodos.requestFocus();
            listarProveedores();
        }
    }//GEN-LAST:event_txtBusquedaKeyReleased

    private void btnEstCuentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEstCuentaActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (jTable1.getRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No existen proveedores para consultar cuenta...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() == 0){
            JOptionPane.showMessageDialog(this, "No ha seleccionado ningun proveedor para consultar la cuenta...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (jTable1.getSelectedRowCount() == 1 ) {
            CuentaProveedores ventaCuentaProv = new CuentaProveedores(this, true);
            ventaCuentaProv.mostrarEstadoCuenta((Proveedor) listaProveedores.get(jTable1.getSelectedRow()));
            ventaCuentaProv.setVisible(true);
        }
        else if (jTable1.getSelectedRowCount() > 1) {
            JOptionPane.showMessageDialog(this, "No puede consultar mas de una cuenta de proveedor a la vez...", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnEstCuentaActionPerformed

    private void txtBusquedaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtBusquedaFocusLost
        // TODO add your handling code here:
        txtBusqueda.setText("");
    }//GEN-LAST:event_txtBusquedaFocusLost

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnEstCuenta;
    private javax.swing.JButton btnListarTodos;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JButton btnSalir;
    private javax.swing.JButton btnVerDatosComp;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblBuscar;
    private javax.swing.JTextField txtBusqueda;
    // End of variables declaration//GEN-END:variables

    private void estructurarTabla() {
         //Estructuramos el modeloArticulos para la visualizacion en el jtable
        modeloTablaProveeedores.addColumn("CODIGO");
        modeloTablaProveeedores.addColumn("RAZON SOCIAL");
        modeloTablaProveeedores.addColumn("DOMICILIO");
        modeloTablaProveeedores.addColumn("TELEFONO");
        modeloTablaProveeedores.addColumn("E-MAIL");
   

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(50);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(200);
    }

    public void listarProveedores() {
        Connection conn = null;
        listaProveedores = null;
        try {
            conn = AdministradorDeConexiones.obtenerConexion();
            //Recuperamos todos los articulos de la tabla de Articulos
            listaProveedores = ProveedoresDao.getInstance().getTodos(conn);
            this.vaciarModeloProveedores();
            this.cargarModeloProveedores();
        }catch(Exception e) {e.printStackTrace();}
    }

    private void vaciarModeloProveedores() {
        modeloTablaProveeedores.setRowCount(0);
    }

     private void cargarModeloProveedores() {
        Iterator iteraProv = listaProveedores.iterator();
            while (iteraProv.hasNext()) {
                String[] arregloProv = new String[5];
                //Obtenemos cada articulo de la lista
                Proveedor prov = (Proveedor) iteraProv.next();
                arregloProv[0] = String.valueOf(prov.getId());
                arregloProv[1] = prov.getRazSocial();
                arregloProv[2] = prov.getDomicilio();
                arregloProv[3] = prov.getTelefono();
                arregloProv[4] = prov.getMail();
               //Agregamos el arreglo al modelo
                modeloTablaProveeedores.addRow(arregloProv);
            }
    }

    private void filtrarRazonSocial() {
          Connection conn = null;
          try {
              conn = AdministradorDeConexiones.obtenerConexion();
              String aBuscar = txtBusqueda.getText().toUpperCase().trim();
              if (ProveedoresDao.getInstance().existeFiltroProv(conn, aBuscar)) {
                   listaProveedores = null;
                   listaProveedores = ProveedoresDao.getInstance().getProveedorXrazonSocial(conn, aBuscar);
                   this.vaciarModeloProveedores();
                   this.cargarModeloProveedores();
              }
              else {
                   JOptionPane.showMessageDialog(this, "La descripcion no coincide con ningun Proveedor...", "Error", JOptionPane.INFORMATION_MESSAGE);
                   txtBusqueda.setText("");
                   return;
              }
          }catch(Exception e){e.printStackTrace();}
      }
}
